<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="通知类型" prop="notify_type">
        <el-input
          v-model="queryParams.notify_type"
          placeholder="请输入通知类型"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="组织UUID" prop="org_id">
        <el-input
          v-model="queryParams.org_id"
          placeholder="请输入组织UUID"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目UUID" prop="prj_id">
        <el-input
          v-model="queryParams.prj_id"
          placeholder="请输入项目UUID"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备SN" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入设备SN"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:notify:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notify:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="notifyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="通知ID" align="center" prop="id" />
      <el-table-column label="通知类型" align="center" prop="notifyType" />
      <el-table-column label="组织UUID" align="center" prop="orgId" />
      <el-table-column label="项目UUID" align="center" prop="prjId" />
      <el-table-column label="设备SN" align="center" prop="sn" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:notify:edit']"
            >修改</el-button>
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['system:notify:query']"
            >详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:notify:remove']"
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="notifyRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="通知类型" prop="notify_type">
          <el-input v-model="form.notify_type" placeholder="请输入通知类型" />
        </el-form-item>
        <el-form-item label="组织UUID" prop="org_id">
          <el-input v-model="form.org_id" placeholder="请输入组织UUID" />
        </el-form-item>
        <el-form-item label="项目UUID" prop="prj_id">
          <el-input v-model="form.prj_id" placeholder="请输入项目UUID" />
        </el-form-item>
        <el-form-item label="设备SN" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入设备SN" />
        </el-form-item>
        <el-form-item label="任务类型" prop="task_info.task_type">
          <el-input v-model="form.task_info.task_type" placeholder="请输入任务类型" />
        </el-form-item>
        <el-form-item label="任务标签" prop="task_info.tags">
          <el-input
            v-model="tagInput"
            placeholder="请输入任务标签,多个标签用英文逗号分隔"
            @change="handleTagsChange"
          />
          <div class="form-tips">提示: 多个标签请用英文逗号分隔,如: 标签1,标签2,标签3</div>
        </el-form-item>
        <el-form-item label="任务ID" prop="task_info.task_id">
          <el-input v-model="form.task_info.task_id" placeholder="请输入任务ID" />
        </el-form-item>
        <el-form-item label="预期文件数量" prop="folder_info.expected_file_count">
          <el-input-number v-model="form.folder_info.expected_file_count" :min="0" />
        </el-form-item>
        <el-form-item label="已上传文件数量" prop="folder_info.uploaded_file_count">
          <el-input-number v-model="form.folder_info.uploaded_file_count" :min="0" />
        </el-form-item>
        <el-form-item label="文件夹ID" prop="folder_info.folder_id">
          <el-input-number v-model="form.folder_info.folder_id" :min="0" />
        </el-form-item>
        <el-form-item label="文件列表" prop="files">
          <el-table :data="form.files" border>
            <el-table-column label="文件名" prop="name">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="请输入文件名" />
              </template>
            </el-table-column>
            <el-table-column label="阿里云key" prop="key">
              <template #default="scope">
                <el-input v-model="scope.row.key" placeholder="请输入阿里云key" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template #default="scope">
                <el-button link type="primary" icon="Delete" @click="handleDeleteFile(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button style="margin-top: 10px" @click="handleAddFile">添加文件</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="查看详情" v-model="viewOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="通知类型">{{ viewForm.notifyType }}</el-descriptions-item>
        <el-descriptions-item label="组织UUID">{{ viewForm.orgId }}</el-descriptions-item>
        <el-descriptions-item label="项目UUID">{{ viewForm.prjId }}</el-descriptions-item>
        <el-descriptions-item label="设备SN">{{ viewForm.sn }}</el-descriptions-item>
        <el-descriptions-item label="任务类型">{{ viewForm.taskType }}</el-descriptions-item>
        <el-descriptions-item label="任务标签">{{ viewForm.tags }}</el-descriptions-item>
        <el-descriptions-item label="任务ID">{{ viewForm.taskId }}</el-descriptions-item>
        <el-descriptions-item label="预期文件数量">{{ viewForm.expectedFileCount }}</el-descriptions-item>
        <el-descriptions-item label="已上传文件数量">{{ viewForm.uploadedFileCount }}</el-descriptions-item>
        <el-descriptions-item label="文件夹ID">{{ viewForm.folderId }}</el-descriptions-item>
      </el-descriptions>
      <el-table :data="viewForm.files" border style="margin-top: 20px">
        <el-table-column label="文件名" prop="name" />
        <el-table-column label="阿里云key" prop="key" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Notify">
import { listNotify, addNotify, delNotify, getNotify, updateNotify } from "@/api/notify";

const { proxy } = getCurrentInstance();

const notifyList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    notify_type: undefined,
    org_id: undefined,
    prj_id: undefined,
    sn: undefined,
    task_info: {
      task_type: undefined,
      tags: [],
      task_id: undefined
    },
    folder_info: {
      expected_file_count: 0,
      uploaded_file_count: 0,
      folder_id: 0
    },
    files: []
  },
  viewForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    notify_type: undefined,
    org_id: undefined,
    prj_id: undefined,
    sn: undefined
  },
  rules: {
    notify_type: [{ required: true, message: "通知类型不能为空", trigger: "blur" }],
    org_id: [{ required: true, message: "组织UUID不能为空", trigger: "blur" }],
    prj_id: [{ required: true, message: "项目UUID不能为空", trigger: "blur" }],
    sn: [{ required: true, message: "设备SN不能为空", trigger: "blur" }],
    "task_info.task_type": [{ required: true, message: "任务类型不能为空", trigger: "blur" }],
    "task_info.task_id": [{ required: true, message: "任务ID不能为空", trigger: "blur" }]
  },
  tagInput: ''
});

const { queryParams, form, rules, viewForm, tagInput } = toRefs(data);

/** 查询通知列表 */
function getList() {
  loading.value = true;
  listNotify(queryParams.value).then(response => {
    notifyList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    notify_type: undefined,
    org_id: undefined,
    prj_id: undefined,
    sn: undefined,
    task_info: {
      task_type: undefined,
      tags: [],
      task_id: undefined
    },
    folder_info: {
      expected_file_count: 0,
      uploaded_file_count: 0,
      folder_id: 0
    },
    files: []
  };
  tagInput.value = '';
  proxy.resetForm("notifyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加通知";
}

/** 删除按钮操作 */
function handleDelete(row) {
  const notifyIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除通知编号为"' + notifyIds + '"的数据项？').then(function() {
    return delNotify(notifyIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 查看详情按钮操作 */
function handleView(row) {
  reset();
  const id = row.id;
  getNotify(id).then(response => {
    viewForm.value = response.data;
    if(response.data.task_info?.tags) {
      tagInput.value = response.data.task_info.tags.join(',');
    }
    viewOpen.value = true;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id;
  getNotify(id).then(response => {
    form.value = {
      id: response.data.id,
      notify_type: response.data.notifyType,
      org_id: response.data.orgId,
      prj_id: response.data.prjId,
      sn: response.data.sn,
      task_info: {
        task_type: response.data.taskType,
        tags: response.data.tags ? response.data.tags.split(',') : [],
        task_id: response.data.taskId
      },
      folder_info: {
        expected_file_count: response.data.expectedFileCount,
        uploaded_file_count: response.data.uploadedFileCount,
        folder_id: response.data.folderId
      },
      files: response.data.files || []
    };
    // 设置标签输入框的值
    tagInput.value = response.data.tags || '';
    open.value = true;
    title.value = "修改通知";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["notifyRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        updateNotify(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addNotify(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 文件相关操作 */
function handleAddFile() {
  form.value.files.push({
    name: '',
    key: ''
  });
}

function handleDeleteFile(index) {
  form.value.files.splice(index, 1);
}

function handleTagsChange(value) {
  if(!value) {
    form.value.task_info.tags = [];
    return;
  }
  form.value.task_info.tags = value.split(',').map(tag => tag.trim()).filter(tag => tag);
}

getList();
</script>

<style scoped>
.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 